package com.qmq.app.controller;


import com.qmq.app.entity.UserEntity;
import com.qmq.app.form.LoginForm;
import com.qmq.app.service.UserService;
import com.qmq.app.utils.JwtUtils;
import com.qmq.app.utils.StrUtils;
import com.qmq.common.exception.RRException;
import com.qmq.common.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * APP登录授权
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/app")
@Api("APP登录接口")
public class AppLoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 登录
     */
    @PostMapping("login")
    @ApiOperation("登录")
    public R login(@RequestBody @Validated LoginForm form) {
        if (!StrUtils.isEmail(form.getMobile())) {
            throw new RRException("邮箱格式错误");
        }
        //用户登录
        UserEntity user = userService.login(form);

        //生成token
        String token = jwtUtils.generateToken(user.getUserId());

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());
        map.put("data", user);
        return R.ok(map);
    }

}
